package com.jing.yao.security.handler;

import com.jing.yao.bean.ResponseBean;
import com.jing.yao.cache.CacheHelper;
import com.jing.yao.cache.RedisKeyEnum;
import com.jing.yao.code.UserCode;
import com.jing.yao.component.constants.BmsConstants;
import com.jing.yao.i18.MessageSourceHolder;
import com.jing.yao.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * 登录成功
 *
 * @author lirui
 * @since 2020-06-24
 */
public class YaoLoginSuccessHandler implements AuthenticationSuccessHandler {

    private final static String SECRET_KEY = "anji-plus";

    @Autowired
    private CacheHelper cacheHelper;
    @Autowired
    private MessageSourceHolder messageSourceHolder;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding(BmsConstants.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String code = UserCode.USER_LOGIN_SUCCESS;
        ResponseBean.Builder builder = ResponseBean.builder();
        String username = authentication.getName();

        //该用户独有的私钥
        String token = JwtUtils.createToken(username);

        //保存登录token
        cacheHelper.hashSet(RedisKeyEnum.TOKEN_JWT_USER.getKey(), username, token);

        //保存权限并清空旧的权限
        String[] authorities =
                authentication.getAuthorities()
                        .stream()
                        .map(GrantedAuthority::getAuthority)
                        .collect(Collectors.toList())
                        .toArray(new String[]{});

        cacheHelper.setAdd(RedisKeyEnum.USER_AUTHORITIES.getKey() + username, authorities, true);

        ResponseBean responseBean = builder.content(token).build();
        responseBean.setMessage(messageSourceHolder.getMessage(code));
        response.getWriter().print(new ObjectMapper().writeValueAsString(responseBean));
    }
}
